// components/progress-bar/progress-bar.js
let movableAreaWidth = 0//可移动距离
let movableViewWidth = 0//当前进度条移动距离 小白点
let currentSec = -1 //ontimeupdate秒数取整
let duration = 0 //当前歌曲总时长，秒为单位
let isMoving = false // 表示当前进度条是否在拖拽  解决进度条拖动 和 updatetime（）冲突


const backgroundAudioManager = wx.getBackgroundAudioManager()
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    showTime: {
      currentTime: '00:00',
      totalTime: '00:00',
    },
    movbableDis: 0,   //可移动距离
    progress: 0 , //当前进度条移动距离
  },

  
  //生命周期函数  
  //组件在页面布局完成后执行
  lifetimes: {
    ready(){
      this._getMovableDis()
      this._bindBGMEvent()
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onChange(event){
      console.log(event)
      //拖动进度条
      if (event.detail.source == 'touch') {
        this.data.progress = event.detail.x / (movableAreaWidth - movableViewWidth) * 100
        this.data.movableDis = event.detail.x
        isMoving = true
      }
    },
    onTouchEnd(){

      const currentTimeFmt = this._dateFormat(Math.floor(backgroundAudioManager.currentTime))
      this.setData({
        progress: this.data.progress, //当前播放进度
        movableDis: this.data.movableDis,
        ['showTime.currentTime']: currentTimeFmt.min+':'+currentTimeFmt.sec
      })
      backgroundAudioManager.seek(duration*this.data.progress / 100)
      isMoving = false
    },

    _getMovableDis(){
      const query = this.createSelectorQuery()//创建一个 SelectorQuery 对象，选择器选取范围为这个组件实例内
      query.select('.movable-area').boundingClientRect()  // 获取 movable-area宽度
      query.select('.movable-view').boundingClientRect()  // 获取 movbale-view宽度、
      query.exec((rect) =>{
        console.log(rect)
        movableAreaWidth = rect[0].width
        movableViewWidth = rect[1].width
      })
  },

  _bindBGMEvent(){
    backgroundAudioManager.onPlay(() => {
      console.log('onPlay')
     isMoving = false
    })

    backgroundAudioManager.onStop(() => {
      console.log('onStop')
    })

    backgroundAudioManager.onPause(() => {
      console.log('Pause')
      
    })

    backgroundAudioManager.onWaiting(() => {
      console.log('onWaiting')
    })

    backgroundAudioManager.onCanplay(() => {
      console.log('onCanplay')
      console.log(backgroundAudioManager.duration)  //duration 背景音乐总时长  可能遇到undefined 以下为优化
      if (typeof backgroundAudioManager.duration != 'undefined') {
        this._setTime()
      } else {  //如果 没获取到时间 则 设置定时器 重新获取
        setTimeout(() => {  
          this._setTime()
        }, 1000)
      }
    })

    backgroundAudioManager.onTimeUpdate(() => {
      console.log('onTimeUpdate')
      
      if (!isMoving) {
        const currentTime = backgroundAudioManager.currentTime // 当前播放时间
        const duration = backgroundAudioManager.duration // 获取歌曲总时长
       
        if (currentTime.toString().split('.')[0] != currentSec) {
          console.log(currentTime)
          const currentTimeFmt = this._dateFormat(currentTime)
          this.setData({
          movableDis: (movableAreaWidth-movableViewWidth)*currentTime/duration,//播放时移动的刻度
          progress: currentTime/duration*100,  //进度百分百  播放的进度颜色
          ['showTime.currentTime'] : `${currentTimeFmt.min}:${currentTimeFmt.sec}`,
        })
  
        currentSec = currentTime.toString().split('.')[0]
         // 联动歌词
         this.triggerEvent('timeUpdate', {
          currentTime
        })

        }
      }


     
    
    })

    backgroundAudioManager.onEnded(() => {
      console.log("onEnded")
      this.triggerEvent('musicEnd')
    })

    backgroundAudioManager.onError((res) => {
      console.error(res.errMsg)
      console.error(res.errCode)
      wx.showToast({
        title: '错误:' + res.errCode,
      })
    })
  },

  _setTime() {
    duration = backgroundAudioManager.duration
    console.log(duration)
    const durationFmt = this._dateFormat(duration)
    console.log(durationFmt)
    this.setData({
      ['showTime.totalTime']: `${durationFmt.min}:${durationFmt.sec}`
      
    })  
    
  },

  // 格式化时间
  _dateFormat(sec) {
    // 分钟
    const min = Math.floor(sec / 60)
    sec = Math.floor(sec % 60)
    return {
      'min': this._parse0(min),
      'sec': this._parse0(sec),
    }
  },
  // 补零
  _parse0(sec) {
    return sec < 10 ? '0' + sec : sec
  }

  }
})
